<script>
	import imService from '@/utils/imService.js';
	import {
		mapActions
	} from 'vuex';
	import notificationService from '@/utils/notificationService.js';

	export default {
		onLaunch: function() {
			// console.log('App Launch');
			// consoloe.log('env', process.env)
			this.$store.commit('LOAD_CHAT_HISTORY_FROM_STORAGE');
			// ============== START: 系统信息计算逻辑 ==============
			// #ifdef MP-WEIXIN || MP-ALIPAY || MP-BAIDU || MP-TOUTIAO || MP-QQ
			try {
				const systemInfo = uni.getSystemInfoSync();
				const capsuleInfo = uni.getMenuButtonBoundingClientRect();

				// 计算自定义导航栏的高度
				const navBarHeight = (capsuleInfo.top - systemInfo.statusBarHeight) * 2 + capsuleInfo.height;

				// 计算胶囊按钮右侧的安全边距
				const capsuleRightPadding = systemInfo.windowWidth - capsuleInfo.right;

				// 提交到 Vuex
				this.$store.commit('SET_SYSTEM_INFO', {
					statusBarHeight: systemInfo.statusBarHeight,
					navBarHeight: navBarHeight,
					capsuleInfo: capsuleInfo,
					navBarTotalHeight: systemInfo.statusBarHeight + navBarHeight,
					capsuleRightPadding: capsuleRightPadding
				});

			} catch (e) {
				console.error("获取系统或胶囊按钮信息失败:", e);
				// 在异常情况下提供备用值
				const systemInfo = uni.getSystemInfoSync();
				this.$store.commit('SET_SYSTEM_INFO', {
					statusBarHeight: systemInfo.statusBarHeight || 20,
					navBarHeight: 44,
					capsuleInfo: {
						width: 87,
						height: 32,
						top: systemInfo.statusBarHeight + 4,
						right: systemInfo.windowWidth - 7
					},
					navBarTotalHeight: (systemInfo.statusBarHeight || 20) + 44,
					capsuleRightPadding: 7
				});
			}
			// #endif
			// ============== END: 系统信息计算逻辑 ==============

			// 1. 初始化IM核心服务和监听器
			this.initIMCore().then(() => {
				console.log("IM Core Service initialized.");
				// 2. 设置全局来电监听
				this.setupCallListener();
				// 应用启动时，尝试进行IM自动登录
				this.tryAutoLoginIM();
			}).catch(err => {
				console.error('IM Core initialization failed in App.vue:', err);
			});

			// 3. 检查并恢复业务登录状态
			const token = uni.getStorageSync('token');
			const userInfo = uni.getStorageSync('userInfo');

			if (token && userInfo && userInfo.userId) {
				this.$store.commit('setUserInfo', userInfo);
				this.$store.commit('login');

				// 4. 如果业务已登录，尝试IM自动登录
				const imUserId = uni.getStorageSync('im_user_id');
				const imToken = uni.getStorageSync('im_token');
				if (imUserId && imToken) {
					this.$store.dispatch('im/login', {
							username: imUserId,
							token: imToken
						})
						.catch(err => console.warn("App.vue: Auto IM login failed on launch", err));
				}
			} else {
				console.log("No active user session found.");
			}
		},
		onShow: function() {
			const cityInfo = uni.getStorageSync('cityInfo');
			if (cityInfo) {
				this.$store.commit('setCityInfo', cityInfo);
			}

			// 从后台切回前台时，检查并恢复IM连接状态
			this.tryAutoLoginIM();
			// 检查IM连接状态，必要时重新连接
			if (this.$store.state.hasLogin) {
				const imUserId = uni.getStorageSync('im_user_id');
				const imToken = uni.getStorageSync('im_token');

				if (imUserId && imToken && !this.$store.getters['im/isImLoggedIn']) {
					// 如果有登录凭证但未连接，尝试重新连接
					this.$store.dispatch('im/login', {
						username: imUserId,
						token: imToken
					}).catch(err => {
						console.warn("App.vue onShow: IM重新连接失败", err);
					});
				}

				// 刷新会话列表
				this.$store.dispatch('im/fetchSessionList');
				this.$store.dispatch('im/fetchTotalUnreadCount');
			}
		},
		onHide: function() {
			console.log('App Hide');
		},
		methods: {
			...mapActions('im', ['initIMCore', 'login']), // 映射action

			/**
			 * @description 尝试IM自动登录。在App启动和切换到前台时调用。
			 */

			tryAutoLoginIM() {
				// 检查条件：业务已登录、IM未连接、且当前没有正在进行中的IM登录操作
				if (this.$store.state.hasLogin && !this.$store.getters['im/isImLoggedIn'] && !this.$store.state.im
					.isLoggingIn) {
						console.log(123,'后台切换到前台=====================================执行了97');
					const imUserId = uni.getStorageSync('im_user_id') || uni.getStorageSync('userInfo').userId;
					const imToken = uni.getStorageSync('im_token') || uni.getStorageSync('im_app_token');;
					if (imUserId && imToken) {
						console.log("App.vue: 检测到业务已登录，尝试自动登录IM...");
						this.login({
							username: imUserId,
							token: imToken
						}).catch(err => {
							console.warn("App.vue: 自动登录IM失败", err);
						});
					} else {
						// 这种情况可能发生在：用户登录了，但获取IM凭证失败。
						// 可以在这里增加重试逻辑，或者仅在控制台警告。
						console.warn("App.vue: 无法自动登录IM，缺少凭证。");
					}
				}
			},

			// tryAutoLoginIM() {
			// 	// 检查条件：业务已登录、IM未连接、且当前没有正在进行中的IM登录操作
			// 	if (this.$store.state.hasLogin && !this.$store.getters['im/isImLoggedIn'] && !this.$store.state.im
			// 		?.isLoggingIn) {
			// 		console.log('进入条件==========================================');
			// 		const imUserId = uni.getStorageSync('im_user_id') || uni.getStorageSync('userInfo')?.userId;
			// 		const imToken = uni.getStorageSync('im_token') || uni.getStorageSync('im_app_token');
			// 		if (imUserId && imToken) {
			// 			console.log("App.vue: 检测到业务已登录，尝试自动登录IM...");
			// 			// 使用映射的方法调用
			// 			this.login({
			// 				username: imUserId,
			// 				token: imToken
			// 			}).then(() => {
			// 				console.log("IM自动登录成功");
			// 			}).catch(err => {
			// 				console.warn("App.vue: 自动登录IM失败", err);
			// 			});
			// 		} else {
			// 			console.warn("App.vue: 无法自动登录IM，缺少凭证。");
			// 		}
			// 	}
			// },
			setupCallListener() {
				imService.eventBus.$off('im_incoming_call'); // 先移除，防止重复监听
				imService.eventBus.$on('im_incoming_call', (inviteMessage) => {
					console.log('App.vue 收到来电:', inviteMessage);

					const {
						from,
						ext
					} = inviteMessage;
					const {
						channelName,
						agoraToken,
						callerAvatar,
						callerNickname
					} = ext;
					const callType = inviteMessage.type === 'video' ? 'video' : 'voice';

					const callParams = {
						isCaller: false,
						inviteMessage: inviteMessage,
						callType: callType,
						channelName: channelName,
						agoraToken: agoraToken,
						targetUser: {
							id: from,
							name: callerNickname || from,
							avatar: callerAvatar
						}
					};

					// 直接跳转到通话页面
					uni.navigateTo({
						url: `/pages_sub/call/call?params=${encodeURIComponent(JSON.stringify(callParams))}`
					});
				});
			}
		}
	}
</script>

<style lang="scss">
	@import "@/static/iconfont/tabbar/iconfont.css";
	@import "@/static/iconfont/user/iconfont.css";
	@import "@/static/iconfont/index/iconfont.css";
	@import "@/static/iconfont/release/iconfont.css";
	@import "uni_modules/uview-ui/index.scss";

	page {
		// background-color: #F8F8F8;
	}

	/* 其他全局样式 */
	:root {
		--nav-height: 100rpx;
		/* 导航栏高度 */
	}

	.content {
		padding-bottom: var(--nav-height);
		/* 使用变量 */
	}

	.page-content {
		height: calc(100vh - 130rpx);
	}
</style>